import { Button, Drawer, Form, Input, Select } from 'antd';
import _ from 'lodash';
import { useState } from 'react';

import styles from './index.less';
import { debuggerService } from './service';

interface DrawerProps {
  visible: boolean;
  contentItem: any[];
  editItem: IFormEventObj;
  onCancel: () => void;
}
const initialObj = {
  apiResult: {
    request: {
      headers: {},
      method: '',
      body: '{}',
      url: '',
    },
    responseType: 'json',
    responseContent: '',
  },

  value: {},
};

const DebuggerDrawer: React.FC<DrawerProps> = ({ visible, onCancel, editItem, contentItem }) => {
  const arr = _.uniq([...(editItem.action_rely || []), ...(editItem.request_rely || [])]);
  const renderArr = contentItem.filter((item) => arr.includes(item.id));
  const [responseData, setResponseData] = useState<IRequestRes>(initialObj);
  const [loading, setLoading] = useState(true);
  const [form] = Form.useForm();
  const componentsObj = {
    input: Input,
    textarea: Input.TextArea,
    select: Select,
  };
  const handleRequest = async () => {
    console.log(editItem);
    const pannet = /(?<=\$\{)[^}]*(?=\})/g;
    let { url } = editItem.request;
    const postObj = {};
    if (editItem.request.method === 'post') {
      const { body } = editItem.request;
      body.forEach((item) => {
        let { value } = item;
        const params = value.match(pannet) || [];
        params.forEach((param) => {
          const re = new RegExp(`\\$\\{${param}\\}`, 'g');
          value = value.replace(re, form.getFieldValue(param) || '');
        });
        postObj[item.name] = value || '';
      });
    } else {
      if (url.includes('?')) {
        console.log(url);
        const params = url.match(pannet) || [];
        params.forEach((item) => {
          const re = new RegExp(`\\$\\{${item}\\}`, 'g');
          url = url.replace(re, form.getFieldValue(item) || '');
        });
        console.log(url);
      }
    }
    const data = {
      url: url,
      methodType: editItem.request.method,
      data: JSON.stringify(postObj),
      header: editItem.request.header,
      action: editItem.action,
    };
    setLoading(true);
    const result = await debuggerService(data);
    if (result.errorCode === '0') {
      const resData = result.data;
      setResponseData(resData);
      setLoading(false);
      const eventData = resData.apiResult.responseContent;
      const action = resData.value;
      const pannet1 = /(\$\{).*?(\})/g;
      Object.keys(action).forEach((key) => {
        action[key] = action[key].replace(pannet1, (word: string) => {
          const newWord = word.replace(/(\$\{)|(\})/g, '');
          if (newWord.includes('[') && newWord.includes(']')) {
            const newFn = new Function(`return ${eventData}['data']${newWord}`);
            return newFn();
          } else {
            return form.getFieldValue(newWord);
          }
        });
      });
      form.setFieldsValue(action);
    }
  };
  const { headers } = responseData.apiResult.request;
  const body = JSON.parse(responseData.apiResult.request.body);

  return (
    <Drawer
      title="前端事件调试"
      placement="bottom"
      height="95%"
      closable={true}
      onClose={onCancel}
      visible={visible}
      headerStyle={{ textAlign: 'center' }}
      bodyStyle={{ background: '#F4F5F5' }}
      key="bottom2"
    >
      <div className={styles.debuggerWrapper}>
        <div className={styles.debuggerForm}>
          <div className={styles.debuggerTitle}>请填写字段并发送请求</div>
          <div className={styles.debuggerBody}>
            <div className={styles.widgetsWrapper}>
              <Form layout="vertical" form={form}>
                {renderArr.map((item) => {
                  let type = item.name;
                  if (type === 'input' && item.props.textarea) {
                    type = 'textarea';
                  }
                  const Tag = componentsObj[type];
                  return (
                    <Form.Item label={item.title} name={item.id} style={{ width: 350 }}>
                      <Tag {...item.props} />
                    </Form.Item>
                  );
                })}
              </Form>
            </div>
            <div className={styles.footer}>
              <Button key="submit" type="primary" onClick={handleRequest}>
                发送请求
              </Button>
            </div>
          </div>
        </div>
        <div className={styles.debuggerInfo}>
          <div className={styles.debuggerTitle}>调试信息</div>
          <div className={styles.debuggerBody}>
            <div className={styles.contentBlock}>
              <div className={styles.subTitle}>
                请求内容<span className={styles.tip}>（触发前端事件后自动刷新）</span>
              </div>
              <div className={styles.requestContent}>
                {!loading && (
                  <>
                    <div className={styles.label}>请求方式</div>
                    <div className={styles.value}>{responseData.apiResult.request.method}</div>
                    <div className={styles.label}>URL</div>
                    <div className={styles.value}>{responseData.apiResult.request.url}</div>
                    {Object.keys(headers).length > 0 && (
                      <>
                        <div className={styles.label}>Header</div>
                        <div className={styles.headerValue}>
                          {Object.keys(headers).map((key) => (
                            <div className={styles.line}>
                              {key}：{headers[key]}
                            </div>
                          ))}
                        </div>
                      </>
                    )}
                    {Object.keys(body).length > 0 && (
                      <>
                        <div className={styles.label}>Body</div>
                        <div className={styles.bodyValue}>
                          {Object.keys(body).map((key) => (
                            <div className={styles.line}>
                              {key}：{body[key]}
                            </div>
                          ))}
                        </div>
                      </>
                    )}
                  </>
                )}
              </div>
            </div>
            <div className={styles.contentBlock}>
              <div className={styles.subTitle}>
                返回内容<span className={styles.tip}>（触发前端事件后自动刷新）</span>
              </div>
              <div className={styles.responseContent}>
                {!loading && (
                  <>
                    {responseData.apiResult.responseContent ? (
                      responseData.apiResult.responseContent
                    ) : (
                      <div className={styles.errorTip}>请求失败，请检查配置</div>
                    )}
                  </>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
    </Drawer>
  );
};

export default DebuggerDrawer;
